var express = require('express')
const models = require("../../models");
const {success, error} = require("../../utils/message");
var router = express.Router()
const checkPermission = require('../../middlewares/check-permission')

// 广告列表
router.get('/', checkPermission(), async function (req, res, next) {
    let adverts = await models.Advert.findAll({
        order: [
            ['sort', 'DESC'],
        ],
    })
    success(res, '查询成功', {adverts})
})

// 新增广告
router.post('/', checkPermission(), async function (req, res, next) {
    const name = req.body.name

    if (!name) {
        return error(res, '请填写广告名称')
    }

    const advertName = await models.Advert.findOne({where: {name: name}})
    if (advertName) {
        return error(res, '广告名称已存在，请勿重复添加')
    }

    let advert = await models.Advert.create(req.body)
    success(res, '新增成功', {advert})
});

// 查询单条广告
router.get('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id

    const advert = await models.Advert.findByPk(id)
    if (!advert) {
        return error(res, '当前广告不存在，无法修改')
    }

    success(res, '查询成功', {advert})
})

// 修改广告
router.put('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id
    const name = req.body.name

    if (!name) {
        return error(res, '请填写广告名称')
    }

    const advert = await models.Advert.findByPk(id)
    if (!advert) {
        return error(res, '当前广告不存在，无法修改')
    }

    advert.update(req.body)
    success(res, '修改成功', {advert})
})

// 删除广告
router.delete('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id

    const advert = await models.Advert.findOne({
        where: {id: id},
    })

    advert.destroy()
    success(res, '删除成功')
})

// 修改排序
router.patch('/:id/change_sort', checkPermission(), async function (req, res, next) {
    const id = req.params.id
    const sort = req.body.sort

    const advert = await models.Advert.findByPk(id)
    if (!advert) {
        return error(res, '当前快递不存在，无法修改排序')
    }

    if (!sort) {
        return error(res, '请填写排序')
    }

    if (!Number(sort)) {
        return error(res, '排序必须是数字')
    }

    advert.update({ sort: sort })
    success(res, '修改排序成功 ')
})
module.exports = router
